package com.gistmap.sideline.util;

import com.gistmap.sideline.payload.Result;
import com.gistmap.sideline.payload.VerifiedRequest;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;


@Slf4j
public enum  HttpUtil {

    INSTANCE;

    public static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");

    private static OkHttpClient client;

    static {
        client = new OkHttpClient();
    }

    public static String postByJson(String url, String json) throws IOException {
        log.info("## url : {} , ## data : {}" , url, json);
        RequestBody body = RequestBody.create(JSON , json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            log.info("## response data : {}" , response.body().string());
            return response.body().string();
        }

    }

    public static Response vertifiedPost(VerifiedRequest verifiedRequest) throws IOException {
        FormBody.Builder formBuilder = new FormBody.Builder();
        formBuilder.add("name", verifiedRequest.getName());
        formBuilder.add("idcard", verifiedRequest.getCode());
        FormBody body = formBuilder.build();
        Request request = new Request.Builder()
                .url(AppConstants.VERTIFIED_URL)
                .addHeader("Authorization", "APPCODE " + AppConstants.AppCode)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        log.info("返回状态码 : {},message: {}",response.code() , response.message());
        return response;
    }
}
